package com.co.ud.icehome.connector;

import java.util.Properties;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.apache.log4j.Logger;

/**
 * A simple polymorphic JMS producer which can work with Queues or Topics which
 * uses JNDI to lookup the JMS connection factory and destination
 * 
 * 
 */
public final class SimpleProducer {

	private Context jndiContext = null;
	private ConnectionFactory connectionFactory = null;
	private Connection connection = null;
	private Session session = null;
	private Destination destination = null;
	private MessageProducer producer = null;
	private String destinationName = "IceHomeRequestQueue";
	
	private Logger logger = Logger.getLogger(this.getClass());

	public SimpleProducer() {

		/*
		 * Create a JNDI API InitialContext object
		 */
		try {

			Properties props = new Properties();
			props.setProperty(Context.INITIAL_CONTEXT_FACTORY,
					"org.apache.activemq.jndi.ActiveMQInitialContextFactory");
			props.setProperty(Context.PROVIDER_URL, "tcp://localhost:61616");

			jndiContext = new InitialContext(props);
			logger.info("contexto inicializado");

			/*
			 * Look up connection factory and destination.
			 */

			connectionFactory = (ConnectionFactory) jndiContext.lookup("ConnectionFactory");
			destination = (Destination) jndiContext.lookup(destinationName);
			logger.info("look up colas");

			/*
			 * Create connection. Create session from connection; false means
			 * session is not transacted. Create sender and text message. Send
			 * messages, varying text slightly. Send end-of-messages message.
			 * Finally, close connection.
			 */

			connection = connectionFactory.createConnection();
			logger.info("coneccion creada");
			session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
			logger.info("session establecida");
			producer = session.createProducer(destination);
			logger.info("producer crerado");
			

		} catch (JMSException e) {
			logger.error(e);

		} catch (NamingException e) {
			// TODO Auto-generated catch block
			logger.error(e);
		}

	}

	public void sendMessage(String Message) throws JMSException {
		logger.info("send message method");
		TextMessage message = session.createTextMessage();
		message.setText(Message);
		producer.send(message);
		System.out.println("Sending message: " + message);

	}

}
